import React, { useEffect, useState } from 'react';
import { Card, Descriptions, Button, Spin, message } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { createStyles } from 'antd-style';
import CustomPageContainer from '@/components/CustomPageContainer';
import { positionDetail } from '@/services/system/postmanagement';
import { deptpage } from '@/services/system/departmentmanage';
import { useModel } from '@umijs/max';

const useStyles = createStyles(({ token }) => ({
  container: {
    padding: '24px',
    background: '#f5f5f5',
    minHeight: 'calc(100vh - 48px)',
  },
  card: {
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.15)',
  },
  contentContainer: {
    maxWidth: '800px',
    margin: '0 auto',
    padding: '24px',
  },
  title: {
    fontSize: '16px',
    fontWeight: 'bold',
    color: '#1890ff',
    borderBottom: '2px solid #1890ff',
    paddingBottom: '8px',
    marginBottom: '24px',
  },
  descriptions: {
    marginTop: '24px',
    '& .ant-descriptions-item-label': {
      fontWeight: 500,
      color: '#333',
      width: '120px',
      backgroundColor: '#fafafa',
    },
    '& .ant-descriptions-item-content': {
      color: '#666',
    },
  },
  buttonGroup: {
    display: 'flex',
    justifyContent: 'center',
    gap: '16px',
    marginTop: '32px',
  },
  button: {
    width: '120px',
    height: '36px',
    borderRadius: '4px',
    fontSize: '14px',
  },
}));

interface DeptTreeItem {
  id: number;
  departmentId: string;
  deptName: string;
  fullName: string;
  deptCategory: number;
  parementId: string | null;
  ancestors: string;
  children?: DeptTreeItem[];
  isDeleted: number;
  remark: string;
  sort: number;
}

const PostManagementView: React.FC = () => {
  const { styles } = useStyles();
  const location = useLocation();
  const navigate = useNavigate();
  const { record } = location.state || {};
  const [loading, setLoading] = useState(false);
  const [detailData, setDetailData] = useState<any>(null);
  const [parentDeptName, setParentDeptName] = useState<string>('');
  const { institutionId, institutionRoleId } = useModel('auth');

  const findParentDeptName = (deptList: DeptTreeItem[], targetId: string): string => {
    for (const dept of deptList) {
      if (dept.departmentId === targetId) {
        return dept.deptName;
      }
      if (dept.children) {
        const found = findParentDeptName(dept.children, targetId);
        if (found) return found;
      }
    }
    return '';
  };


  const fetchDetailData = async () => {
    if (!record?.positionId) return;
    setLoading(true);
    try {
      const detailRes = await positionDetail({
        positionId: record.positionId,
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
      });
      if (detailRes.code === 200) {
        setDetailData(detailRes.data);
      } else {
        message.error('获取岗位详情失败');
        navigate('/system/postmanagement');
      }
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
      navigate('/system/postmanagement');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDetailData();
  }, [record?.positionId]);

  return (
    <CustomPageContainer>
      <div className={styles.container}>
        <Card className={styles.card}>
          <div className={styles.contentContainer}>
            <div className={styles.title}>岗位详情</div>
            <Spin spinning={loading}>
              <Descriptions
                bordered
                column={1}
                className={styles.descriptions}
                size="middle"
              >
                <Descriptions.Item label="岗位名称">{detailData?.positionName}</Descriptions.Item>
                <Descriptions.Item label="岗位编号">{detailData?.positionId}</Descriptions.Item>
                <Descriptions.Item label="岗位排序">{detailData?.sort}</Descriptions.Item>
                <Descriptions.Item label="上级部门">{detailData?.departmentName ? detailData?.departmentName : '顶级'}</Descriptions.Item>
                <Descriptions.Item label="岗位备注">{detailData?.description || '暂无备注'}</Descriptions.Item>
              </Descriptions>
            </Spin>
            <div className={styles.buttonGroup}>
              <Button
                className={styles.button}
                onClick={() => navigate('/system/postmanagement')}
                disabled={loading}
              >
                返回
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </CustomPageContainer>
  );
};

export default PostManagementView;
